package com.bbb.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.extension.api.R;
import com.bbb.common.Code;
import com.bbb.common.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/works/file")
public class WorksFileController {
    /**
     * 上传文件
     *
     * @param file 要上传的文件
     * @return 返回上传结果的封装对象
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = file.getInputStream(); // 获取文件输入流
            byte[] buffer = new byte[in.available()]; // 创建缓冲区
            in.read(buffer); // 读取文件内容
            String fileName = UUID.randomUUID() + "." + getFileExtension(file);
            // 构建上传文件的目标路径
            String upload = System.getProperty("user.dir") + File.separator + "target" + File.separator + "classes" + File.separator + "static" + File.separator + "upload";
            upload += File.separator + fileName;
            out = new FileOutputStream(upload); // 创建输出流
            out.write(buffer); // 写入文件内容

            FileUtil.writeBytes(buffer, System.getProperty("user.dir") + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "static" + File.separator + "upload" + File.separator + fileName );
            return new Result(Code.GET_OK, "上传成功", "/api/upload/" + fileName);
        } catch (IOException e) {
            e.printStackTrace(); // 输出异常信息
        } finally {
            // 关闭输入流
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            // 关闭输出流
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return new Result(Code.GET_ERR, "上传失败");
    }

    public static String getFileExtension(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        int dotIndex = fileName.lastIndexOf(".");
        if (dotIndex == -1) {
            return "";
        } else {
            return fileName.substring(dotIndex + 1);
        }
    }

}
